package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"
)

type BlogPost struct {
	Title   string    `json:"title"`
	Content string    `json:"content"`
	Author  string    `json:"author"`
	Date    time.Time `json:"date"`
}

func encodeToJSON(post BlogPost) ([]byte, error) {
	return json.Marshal(post)
}

func decodeFromJSON(jsonBytes []byte) (BlogPost, error) {
	var post BlogPost
	err := json.Unmarshal(jsonBytes, &post)
	return post, err
}

func savePostToFile(filename string, post BlogPost) error {
	jsonBytes, err := encodeToJSON(post)
	if err != nil {
		return err
	}
	return os.WriteFile(filename, jsonBytes, 0644)
}

func loadPostFromFile(filename string) (BlogPost, error) {
	jsonBytes, err := os.ReadFile(filename)
	if err != nil {
		return BlogPost{}, err
	}
	return decodeFromJSON(jsonBytes)
}

func main() {
	// 使用上述函数
	post := BlogPost{
		Title:   "My First Blog Post",
		Content: "Content of my first blog post",
		Author:  "John Doe",
		Date:    time.Now(),
	}

	filename := "post.json"

	// 保存博客文章到文件
	err := savePostToFile(filename, post)
	if err != nil {
		log.Fatal(err)
	}

	// 从文件中读取博客文章
	loadedPost, err := loadPostFromFile(filename)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Loaded blog post:", loadedPost)
}
